[[...path]].page.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. isClient, isIPageInfoForEntity, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import type {
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUser, IUserHasId,
  8. } from '@growi/core';
  9. import ExtensibleCustomError from 'extensible-custom-error';
  10. import {
  11. GetServerSideProps, GetServerSidePropsContext,
  12. } from 'next';
  13. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  14. import dynamic from 'next/dynamic';
  15. import Head from 'next/head';
  16. import { useRouter } from 'next/router';
  17. import superjson from 'superjson';
  18. import { useCurrentGrowiLayoutFluidClassName } from '~/client/services/layout';
  19. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  20. import type { CrowiRequest } from '~/interfaces/crowi-request';
  21. import type { EditorConfig } from '~/interfaces/editor-settings';
  22. import type { IPageGrantData } from '~/interfaces/page';
  23. import type { RendererConfig } from '~/interfaces/services/renderer';
  24. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  25. import type { IUserUISettings } from '~/interfaces/user-ui-settings';
  26. import type { PageModel, PageDocument } from '~/server/models/page';
  27. import type { PageRedirectModel } from '~/server/models/page-redirect';
  28. import type { UserUISettingsModel } from '~/server/models/user-ui-settings';
  29. import { useEditingMarkdown } from '~/stores/editor';
  30. import { useHasDraftOnHackmd, usePageIdOnHackmd, useRevisionIdHackmdSynced } from '~/stores/hackmd';
  31. import { useSWRxCurrentPage, useSWRxIsGrantNormalized } from '~/stores/page';
  32. import { useRedirectFrom } from '~/stores/page-redirect';
  33. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  34. import {
  35. useSelectedGrant,
  36. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth,
  37. } from '~/stores/ui';
  38. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  39. import loggerFactory from '~/utils/logger';
  40. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  41. import { BasicLayoutWithEditorMode } from '../components/Layout/BasicLayout';
  42. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  43. import { DisplaySwitcher } from '../components/Page/DisplaySwitcher';
  44. import {
  45. useCurrentUser,
  46. useIsLatestRevision,
  47. useIsForbidden, useIsNotFound, useIsSharedUser,
  48. useIsEnabledStaleNotification, useIsIdenticalPath,
  49. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  50. useDrawioUri, useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  51. useIsAclEnabled, useIsSearchPage, useTemplateTagData, useTemplateBodyData, useIsEnabledAttachTitleHeader,
  52. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  53. useIsSlackConfigured, useRendererConfig,
  54. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useIsContainerFluid, useIsNotCreatable,
  55. } from '../stores/context';
  56. import { NextPageWithLayout } from './_app.page';
  57. import {
  58. CommonProps, getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage,
  59. } from './utils/commons';
  60. declare global {
  61. // eslint-disable-next-line vars-on-top, no-var
  62. var globalEmitter: EventEmitter;
  63. }
  64. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  65. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher')
  66. .then(mod => mod.GrowiSubNavigationSwitcher), { ssr: false });
  67. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  68. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  69. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  70. const logger = loggerFactory('growi:pages:all');
  71. const {
  72. isPermalink: _isPermalink, isTrashPage: _isTrashPage, isCreatablePage,
  73. } = pagePathUtils;
  74. const { removeHeadingSlash } = pathUtils;
  75. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  76. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  77. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  78. {
  79. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  80. return v?.data != null
  81. && v?.data.toObject != null
  82. && v?.meta != null
  83. && isIPageInfoForEntity(v.meta);
  84. },
  85. serialize: (v) => {
  86. return {
  87. data: superjson.stringify(v.data.toObject()),
  88. meta: superjson.stringify(v.meta),
  89. };
  90. },
  91. deserialize: (v) => {
  92. return {
  93. data: superjson.parse(v.data),
  94. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  95. };
  96. },
  97. },
  98. 'IPageToShowRevisionWithMetaTransformer',
  99. );
  100. // GrowiContextualSubNavigation for NOT shared page
  101. type GrowiContextualSubNavigationProps = {
  102. isLinkSharingDisabled: boolean,
  103. }
  104. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  105. const { isLinkSharingDisabled } = props;
  106. const { data: currentPage } = useSWRxCurrentPage();
  107. return (
  108. <div data-testid="grw-contextual-sub-nav">
  109. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled}/>
  110. </div>
  111. );
  112. };
  113. const PutbackPageModal = (): JSX.Element => {
  114. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  115. return <PutbackPageModal />;
  116. };
  117. type Props = CommonProps & {
  118. currentUser: IUser,
  119. pageWithMeta: IPageToShowRevisionWithMeta | null,
  120. // pageUser?: any,
  121. redirectFrom?: string;
  122. // shareLinkId?: string;
  123. isLatestRevision?: boolean,
  124. isIdenticalPathPage?: boolean,
  125. isForbidden: boolean,
  126. isNotFound: boolean,
  127. isNotCreatable: boolean,
  128. // isAbleToDeleteCompletely: boolean,
  129. templateTagData?: string[],
  130. templateBodyData?: string,
  131. isSearchServiceConfigured: boolean,
  132. isSearchServiceReachable: boolean,
  133. isSearchScopeChildrenAsDefault: boolean,
  134. isSlackConfigured: boolean,
  135. // isMailerSetup: boolean,
  136. isAclEnabled: boolean,
  137. // hasSlackConfig: boolean,
  138. drawioUri: string | null,
  139. hackmdUri: string,
  140. noCdn: string,
  141. // highlightJsStyle: string,
  142. isAllReplyShown: boolean,
  143. isContainerFluid: boolean,
  144. editorConfig: EditorConfig,
  145. isEnabledStaleNotification: boolean,
  146. isEnabledAttachTitleHeader: boolean,
  147. // isEnabledLinebreaks: boolean,
  148. // isEnabledLinebreaksInComments: boolean,
  149. adminPreferredIndentSize: number,
  150. isIndentSizeForced: boolean,
  151. disableLinkSharing: boolean,
  152. grantData?: IPageGrantData,
  153. rendererConfig: RendererConfig,
  154. // UI
  155. userUISettings?: IUserUISettings
  156. // Sidebar
  157. sidebarConfig: ISidebarConfig,
  158. };
  159. const Page: NextPageWithLayout<Props> = (props: Props) => {
  160. // const { t } = useTranslation();
  161. const router = useRouter();
  162. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  163. // register global EventEmitter
  164. if (isClient() && window.globalEmitter == null) {
  165. window.globalEmitter = new EventEmitter();
  166. }
  167. // commons
  168. useEditorConfig(props.editorConfig);
  169. useCsrfToken(props.csrfToken);
  170. // UserUISettings
  171. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  172. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  173. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  174. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  175. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  176. // page
  177. useIsLatestRevision(props.isLatestRevision);
  178. useIsContainerFluid(props.isContainerFluid);
  179. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  180. useIsForbidden(props.isForbidden);
  181. useIsNotFound(props.isNotFound);
  182. useIsNotCreatable(props.isNotCreatable);
  183. useRedirectFrom(props.redirectFrom ?? null);
  184. useIsSharedUser(false); // this page cann't be routed for '/share'
  185. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  186. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  187. useIsSearchPage(false);
  188. useTemplateTagData(props.templateTagData);
  189. useTemplateBodyData(props.templateBodyData);
  190. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  191. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  192. useIsSearchServiceReachable(props.isSearchServiceReachable);
  193. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  194. useIsSlackConfigured(props.isSlackConfigured);
  195. // useIsMailerSetup(props.isMailerSetup);
  196. useIsAclEnabled(props.isAclEnabled);
  197. // useHasSlackConfig(props.hasSlackConfig);
  198. useDrawioUri(props.drawioUri);
  199. useHackmdUri(props.hackmdUri);
  200. // useNoCdn(props.noCdn);
  201. useDefaultIndentSize(props.adminPreferredIndentSize);
  202. useIsIndentSizeForced(props.isIndentSizeForced);
  203. useDisableLinkSharing(props.disableLinkSharing);
  204. useRendererConfig(props.rendererConfig);
  205. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  206. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  207. useIsAllReplyShown(props.isAllReplyShown);
  208. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  209. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  210. const { pageWithMeta, userUISettings } = props;
  211. const pageId = pageWithMeta?.data._id;
  212. const pagePath = pageWithMeta?.data.path ?? props.currentPathname;
  213. useCurrentPageId(pageId ?? null);
  214. useRevisionIdHackmdSynced(pageWithMeta?.data.revisionHackmdSynced);
  215. useRemoteRevisionId(pageWithMeta?.data.revision?._id);
  216. usePageIdOnHackmd(pageWithMeta?.data.pageIdOnHackmd);
  217. useHasDraftOnHackmd(pageWithMeta?.data.hasDraftOnHackmd ?? false);
  218. useCurrentPathname(props.currentPathname);
  219. useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  220. useEditingMarkdown(pageWithMeta?.data.revision?.body);
  221. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  222. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  223. useSetupGlobalSocket();
  224. useSetupGlobalSocketForPage(pageId);
  225. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName();
  226. const shouldRenderPutbackPageModal = pageWithMeta != null
  227. ? _isTrashPage(pageWithMeta.data.path)
  228. : false;
  229. // sync grant data
  230. useEffect(() => {
  231. const grantDataToApply = props.grantData ? props.grantData : grantData?.grantData.currentPageGrant;
  232. mutateSelectedGrant(grantDataToApply);
  233. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant, props.grantData]);
  234. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  235. useEffect(() => {
  236. const decodedURI = decodeURI(window.location.pathname);
  237. if (isClient() && decodedURI !== props.currentPathname) {
  238. const { search, hash } = window.location;
  239. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  240. }
  241. }, [props.currentPathname, router]);
  242. const title = generateCustomTitleForPage(props, pagePath);
  243. return (
  244. <>
  245. <Head>
  246. <title>{title}</title>
  247. </Head>
  248. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  249. <header className="py-0 position-relative">
  250. <div id="grw-subnav-container">
  251. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  252. </div>
  253. </header>
  254. <div className="d-edit-none">
  255. <GrowiSubNavigationSwitcher />
  256. </div>
  257. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  258. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  259. <DisplaySwitcher
  260. pagePath={pagePath}
  261. page={pageWithMeta?.data}
  262. isIdenticalPathPage={props.isIdenticalPathPage}
  263. isNotFound={props.isNotFound}
  264. isForbidden={props.isForbidden}
  265. isNotCreatable={props.isNotCreatable}
  266. />
  267. <PageStatusAlert />
  268. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  269. </div>
  270. </>
  271. );
  272. };
  273. Page.getLayout = function getLayout(page) {
  274. return (
  275. <>
  276. <DrawioViewerScript />
  277. <BasicLayoutWithEditorMode>
  278. {page}
  279. </BasicLayoutWithEditorMode>
  280. <UnsavedAlertDialog />
  281. <DescendantsPageListModal />
  282. <DrawioModal />
  283. <HandsontableModal />
  284. </>
  285. );
  286. };
  287. function getPageIdFromPathname(currentPathname: string): string | null {
  288. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  289. }
  290. class MultiplePagesHitsError extends ExtensibleCustomError {
  291. pagePath: string;
  292. constructor(pagePath: string) {
  293. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  294. this.pagePath = pagePath;
  295. }
  296. }
  297. // apply parent page grant fot creating page
  298. async function applyGrantToPage(props: Props, ancestor: any) {
  299. await ancestor.populate('grantedGroup');
  300. const grant = {
  301. grant: ancestor.grant,
  302. };
  303. const grantedGroup = ancestor.grantedGroup ? {
  304. grantedGroup: {
  305. id: ancestor.grantedGroup.id,
  306. name: ancestor.grantedGroup.name,
  307. },
  308. } : {};
  309. props.grantData = Object.assign(grant, grantedGroup);
  310. }
  311. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  312. const { model: mongooseModel } = await import('mongoose');
  313. const req: CrowiRequest = context.req as CrowiRequest;
  314. const { crowi } = req;
  315. const { revisionId } = req.query;
  316. const Page = crowi.model('Page') as PageModel;
  317. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  318. const { pageService } = crowi;
  319. let currentPathname = props.currentPathname;
  320. const pageId = getPageIdFromPathname(currentPathname);
  321. const isPermalink = _isPermalink(currentPathname);
  322. const { user } = req;
  323. if (!isPermalink) {
  324. // check redirects
  325. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  326. if (chains != null) {
  327. // overwrite currentPathname
  328. currentPathname = chains.end.toPath;
  329. props.currentPathname = currentPathname;
  330. // set redirectFrom
  331. props.redirectFrom = chains.start.fromPath;
  332. }
  333. // check whether the specified page path hits to multiple pages
  334. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  335. if (count > 1) {
  336. throw new MultiplePagesHitsError(currentPathname);
  337. }
  338. }
  339. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  340. const page = pageWithMeta?.data as unknown as PageDocument;
  341. // add user to seen users
  342. if (page != null && user != null) {
  343. await page.seen(user);
  344. }
  345. // populate & check if the revision is latest
  346. if (page != null) {
  347. page.initLatestRevisionField(revisionId);
  348. await page.populateDataToShowRevision();
  349. props.isLatestRevision = page.isLatestRevision();
  350. }
  351. if (page == null && user != null) {
  352. const templateData = await Page.findTemplate(props.currentPathname);
  353. if (templateData != null) {
  354. props.templateTagData = templateData.templateTags as string[];
  355. props.templateBodyData = templateData.templateBody as string;
  356. }
  357. // apply pagrent page grant
  358. const ancestor = await Page.findAncestorByPathAndViewer(currentPathname, user);
  359. if (ancestor != null) {
  360. await applyGrantToPage(props, ancestor);
  361. }
  362. }
  363. props.pageWithMeta = pageWithMeta;
  364. }
  365. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  366. const { model: mongooseModel } = await import('mongoose');
  367. const req = context.req as CrowiRequest<IUserHasId & any>;
  368. const { user } = req;
  369. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  370. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  371. if (userUISettings != null) {
  372. props.userUISettings = userUISettings.toObject();
  373. }
  374. }
  375. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  376. const req: CrowiRequest = context.req as CrowiRequest;
  377. const { crowi } = req;
  378. const Page = crowi.model('Page') as PageModel;
  379. const { currentPathname } = props;
  380. const pageId = getPageIdFromPathname(currentPathname);
  381. const isPermalink = _isPermalink(currentPathname);
  382. const page = props.pageWithMeta?.data;
  383. if (props.isIdenticalPathPage) {
  384. props.isNotCreatable = true;
  385. }
  386. else if (page == null) {
  387. props.isNotFound = true;
  388. props.isNotCreatable = !isCreatablePage(currentPathname);
  389. // check the page is forbidden or just does not exist.
  390. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  391. props.isForbidden = count > 0;
  392. }
  393. else {
  394. props.isNotFound = page.isEmpty;
  395. props.isNotCreatable = false;
  396. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  397. if (isPermalink && page.isEmpty) {
  398. props.currentPathname = page.path;
  399. }
  400. // /path/to/page ==> /62a88db47fed8b2d94f30000
  401. if (!isPermalink && !page.isEmpty) {
  402. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  403. if (!isToppage) {
  404. props.currentPathname = `/${page._id}`;
  405. }
  406. }
  407. }
  408. }
  409. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  410. // const req: CrowiRequest = context.req as CrowiRequest;
  411. // const { crowi } = req;
  412. // const UserModel = crowi.model('User');
  413. // if (isUserPage(props.currentPagePath)) {
  414. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  415. // if (user != null) {
  416. // props.pageUser = JSON.stringify(user.toObject());
  417. // }
  418. // }
  419. // }
  420. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  421. const req: CrowiRequest = context.req as CrowiRequest;
  422. const { crowi } = req;
  423. const {
  424. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  425. } = crowi;
  426. props.isSearchServiceConfigured = searchService.isConfigured;
  427. props.isSearchServiceReachable = searchService.isReachable;
  428. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  429. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  430. // props.isMailerSetup = mailService.isMailerSetup;
  431. props.isAclEnabled = aclService.isAclEnabled();
  432. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  433. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  434. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  435. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  436. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  437. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  438. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  439. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  440. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  441. props.editorConfig = {
  442. upload: {
  443. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  444. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  445. },
  446. };
  447. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  448. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  449. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  450. props.rendererConfig = {
  451. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  452. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  453. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  454. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  455. plantumlUri: process.env.PLANTUML_URI ?? null,
  456. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  457. // XSS Options
  458. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  459. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  460. attrWhiteList: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  461. tagWhiteList: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  462. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  463. };
  464. props.sidebarConfig = {
  465. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  466. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  467. };
  468. }
  469. /**
  470. * for Server Side Translations
  471. * @param context
  472. * @param props
  473. * @param namespacesRequired
  474. */
  475. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  476. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  477. props._nextI18Next = nextI18NextConfig._nextI18Next;
  478. }
  479. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  480. const req = context.req as CrowiRequest<IUserHasId & any>;
  481. const { user } = req;
  482. const result = await getServerSideCommonProps(context);
  483. // check for presence
  484. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  485. if (!('props' in result)) {
  486. throw new Error('invalid getSSP result');
  487. }
  488. const props: Props = result.props as Props;
  489. if (props.redirectDestination != null) {
  490. return {
  491. redirect: {
  492. permanent: false,
  493. destination: props.redirectDestination,
  494. },
  495. };
  496. }
  497. if (user != null) {
  498. props.currentUser = user.toObject();
  499. }
  500. try {
  501. await injectPageData(context, props);
  502. }
  503. catch (err) {
  504. if (err instanceof MultiplePagesHitsError) {
  505. props.isIdenticalPathPage = true;
  506. }
  507. else {
  508. throw err;
  509. }
  510. }
  511. await injectUserUISettings(context, props);
  512. await injectRoutingInformation(context, props);
  513. injectServerConfigurations(context, props);
  514. await injectNextI18NextConfigurations(context, props, ['translation']);
  515. return {
  516. props,
  517. };
  518. };
  519. export default Page;